package main

//自定义验证参数
import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gopkg.in/go-playground/validator.v8"
	"net/http"
	"reflect"
	"time"
)

/**
更多信息：https://gopkg.in/go-playground/validator.v8
测试：http://127.0.0.1:8080/bind?check_out=2020-09-09&check_in=2019-07-01&address=hehe&name=tb&age=122
*/
//注意开头字母大小，否则取默认值
type Person struct {
	Name    string `form:"name"  binding:"required"`
	Address string `form:"address" binding:"required"`
	Age     int    `form:"age"  binding:"required,gt=18"` //多个用，隔开
	//bookabledate为自定义标签 ，参考https://gopkg.in/go-playground/validator.v8的Custom Functions
	CheckInTime time.Time `form:"check_in" binding:"required" time_format:"2006-01-02"`
	CheckOutTime time.Time `form:"check_out" binding:"required,gtfield=CheckInTime" time_format:"2006-01-02"`
}



func main() {
	r := gin.Default()

	if v,ok:=binding.Validator.Engine().(*validator.Validate);ok{
		v.RegisterValidation("bookabledate",bookabledate)
	}
	r.GET("/bind", paramsStructBind)
	r.POST("/bind", paramsStructBind)
	r.Run()
}
// 自定义的验证函数，完成首需要注册
func bookabledate(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {

	if date,ok:=field.Interface().(time.Time);ok{
		today:=time.Now()
		if date.Unix() >today.Unix(){
			return true
		}
	}

	return false
}


func paramsStructBind(context *gin.Context) {
	var person Person
	if err := context.ShouldBind(&person); err == nil {
		context.String(http.StatusOK, "%v", person)
	} else {
		context.String(http.StatusBadRequest, "validation err %v", err)
		context.Abort()
		return
	}
}
